from django import forms

# from main.models import Book
from .models import CustomUser
from captcha.fields import CaptchaField


class UserPassWordChangeForm(forms.Form):
    old_password = forms.CharField(label="原始密码", widget=forms.PasswordInput(attrs={
        "class": "form-control",
        "placeholder": "请输入密码"
    }))
    password = forms.CharField(label="密码", widget=forms.PasswordInput(attrs={
        "class": "form-control",
        "placeholder": "请输入密码"
    }))
    password2 = forms.CharField(label="确认密码", widget=forms.PasswordInput(attrs={
        "class": "form-control",
        "placeholder": "请再次输入密码"
    }))

    def clean_password(self):
        password = self.cleaned_data.get('password')
        if len(password) < 6:
            raise forms.ValidationError("密码长度要大于6位")
        return password

    def clean_password2(self):
        password = self.cleaned_data.get('password')
        password2 = self.cleaned_data.get('password2')
        if password != password2:
            raise forms.ValidationError("密码不一致")
        return password2





class UserLoginForm(forms.Form):
    username = forms.CharField(label="用户名/邮箱", widget=forms.TextInput(attrs={
        "class": "form-control",
        "placeholder": "请输入用户名/邮箱"
    }))
    password = forms.CharField(label="密码", widget=forms.PasswordInput(attrs={
        "class": "form-control",
        "placeholder": "请输入密码"
    }))


class UserRegisterForm(forms.ModelForm):
    password = forms.CharField(label="密码", widget=forms.PasswordInput(attrs={
        "class": "form-control",
        "placeholder": "请输入密码"
    }))
    password2 = forms.CharField(label="确认密码", widget=forms.PasswordInput(attrs={
        "class": "form-control",
        "placeholder": "请再次输入密码"
    }))

    captcha = CaptchaField(label="验证码")

    class Meta:
        model = CustomUser
        fields = ['email']
        widgets = {
            'email': forms.EmailInput(attrs={
                "class": "form-control",
                "placeholder": "请输入邮箱"
            }),

        }

    def clean_email(self):
        email = self.cleaned_data.get('email')
        if CustomUser.objects.filter(email=email).exists():
            raise forms.ValidationError("邮箱已经存在")
        return email

    def clean_password(self):
        password = self.cleaned_data.get('password')
        if len(password) < 6:
            raise forms.ValidationError("密码长度要大于6位")
        return password

    def clean_password2(self):
        password = self.cleaned_data.get('password')
        password2 = self.cleaned_data.get('password2')
        if password != password2:
            raise forms.ValidationError("密码不一致")
        return password2




class UserInfoChangeForm(forms.ModelForm):
    class Meta:
        model = CustomUser
        fields = ['head']
        widgets = {
            'head': forms.FileInput(attrs={})
        },
        labels = {
            'head': "头像"
        }

    def clean_head(self):
        head = self.cleaned_data.get('head')
        return head


class UsernameChangeForm(forms.ModelForm):
    """修改用户名的表单类"""

    class Meta:
        model = CustomUser  # 关联用户模型（默认是User，若有自定义用户模型会自动适配）
        fields = ['username']  # 只处理用户名字段
        labels = {
            'username': '新用户名'  # 前端表单显示的标签文字
        }
        widgets = {
            # 为用户名字段添加HTML属性（如placeholder提示、样式等）
            'username': forms.TextInput(attrs={
                'placeholder': '请输入新用户名',
                'class': 'form-control'  # 假设前端用Bootstrap样式
            })
        }

    def clean_username(self):
        """自定义用户名验证逻辑（补充Django默认验证）"""
        username = self.cleaned_data.get('username')

        # self.instance 是表单关联的当前用户对象（在视图中通过instance参数传入）
        if CustomUser.objects.filter(username=username).exclude(pk=self.instance.pk).exists():
            raise forms.ValidationError('该用户名已被使用，请更换其他用户名')

        # 2. 检查用户名长度（假设要求2-20个字符）
        if len(username) < 2 or len(username) > 20:
            raise forms.ValidationError('用户名长度必须在3-20个字符之间')

        return username  # 返回验证通过的用户名




